package com.gitee.ywj1352.算法.week06;

public class 最长回文 {

    public static String longestPalindrome(String s) {
        if (s.length() == 0) {
            return "";
        }
        int start = 0, end = 0;
        for (int i = 0; i < s.length(); i++) {
            int len1 = check(s, i, i);
            int len2 = check(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }


    public static int check1(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            left--;
            right++;
        }
        return right - left - 1;
    }

    public static int check(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            right++;
            left--;
        }
        return right - left - 1;
    }


    public static int check2(String s, int left, int right) {
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            right--;
            left++;
        }
        return right - left - 1;
    }

    public static String longestPalindrome2(String s) {
        char[] chars = s.toCharArray();
        int start = 0, end = 0;
        for (int i = 0; i < chars.length; i++) {
            int len1 = check2(s, i, i);
            int len2 = check2(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end -start){
                end = i + len/2;
                start = i - (len - 1) / 2;
            }
        }
        return s.substring(start, end + 1);
    }


}



